package com.demo.xhfyd;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.eclipse.jetty.util.StringUtil;

import cn.ljl.sand.jws.OutSideDataReceiveItf;
import cn.ljl.sand.jws.OutSideDataReceiveItfPortType;

import com.demo.common.model.Khsx2;
import com.demo.common.model.Ncdzb;
import com.demo.common.model.Xhfyd;
import com.demo.common.model.Xhfymxd;
import com.demo.general.Khsx2Service;
import com.demo.general.NcdzbService;
import com.demo.ncfsjl.NCFSJLService;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Page;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * XhfydService 所有 sql 与业务逻辑写在 Service 中，不要放在 Model 中，更不 要放在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
public class XhfydService {

	@Inject
	XhfydmxService mxservice;
	@Inject
	NCFSJLService fsjlservice;
	@Inject
	Khsx2Service khsx2Service;
	@Inject
	NcdzbService ncdzbService;

	/**
	 * 所有的 dao 对象也放在 Service 中，并且声明为 private，避免 sql 满天飞 sql 只放在业务层，或者放在外部 sql 模板，用模板引擎管理： http://www.jfinal.com/doc/5-13
	 */
	private Xhfyd dao = new Xhfyd().dao();

	public Page<Xhfyd> paginate(int pageNumber, int pageSize) {
		return dao.paginate(pageNumber, pageSize, "select * ", "from XHFYD order by RQ desc");
	}

	public Page<Xhfyd> paginate(int pageNumber, int pageSize, String startDate, String endDate, String djbh, String gysdm, String gysmc, String fkfs) {
		StringBuilder sql = new StringBuilder();
		sql.append(" from XHFYD fy").append(" join (select DJBH,fs.FSMC from XHFYDMX mx join SFKFS fs on fs.FSDM = mx.BYZD3 group by DJBH,fs.FSMC) mx on mx.DJBH = fy.DJBH")
				.append(" join KEHU kh on kh.KHDM = fy.DM2").append(" left join NC_FSJL ls on ls.DJBH = fy.DJBH and RESULT = '1'").append(" WHERE 1 = 1");
		if (StringUtil.isNotBlank(startDate)) {
			sql.append(" AND RQ >= '" + startDate + "'");
		}
		if (StringUtil.isNotBlank(endDate)) {
			sql.append(" AND RQ <= '" + endDate + "'");
		}
		if (StringUtil.isNotBlank(djbh)) {
			sql.append(" and fy.DJBH = '" + djbh + "'");
		}
		if (StringUtil.isNotBlank(gysdm)) {
			sql.append(" and kh.KHDM like '%" + gysdm + "%'");
		}
		if (StringUtil.isNotBlank(gysmc)) {
			sql.append(" and kh.KHMC like '%" + gysmc + "%'");
		}
		sql.append(" ORDER BY RQ DESC");
		return dao.paginate(pageNumber, pageSize,
				"select fy.DJBH,convert(date,fy.RQ) as RQ,convert(decimal(18,2),fy.JE) as JE,kh.KHDM,fy.BZ,kh.KHMC,mx.FSMC,case when NCBILLID is not null then '是' end as issend", sql.toString());
	}

	public Xhfyd findById(String id) {
		return dao.findById(id);
	}

	public void deleteById(String id) {
		dao.deleteById(id);
	}

	public boolean isXml(String str) {
		boolean flag = true;
		try {
			DocumentHelper.parseText(str);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public Document makeXhfydXml(Xhfyd xhfydBean, String ncbillid) throws Exception {

		List<Xhfymxd> listMx = mxservice.find(xhfydBean.getStr("DJBH"));
		if (listMx.size() == 0) {
			throw new Exception("明细为空！");
		}
		Element root = DocumentHelper.createElement("DataBill");
		Document doucment = DocumentHelper.createDocument(root);
		root.addElement("MessageID").addText(xhfydBean.getStr("DJBH"));// 唯一标识，随机字符
		root.addElement("TargetSystem").addText("OMERP");
		root.addElement("billtype").addText("RECBILL");
		root.addElement("description").addText("");
		Khsx2 sx = khsx2Service.findByKHDM(xhfydBean.getStr("DM2"));
		Element mainTable = root.addElement("maintable");
		mainTable.addElement("billid").addText(ncbillid);// 单据id，由查询接口返回，新增时此节点值为空，修改时不能为空
		String pk_org = StringUtil.isBlank(sx.getStr("BYZD1")) == true ? "01" : sx.getStr("BYZD1");
		mainTable.addElement("pk_org").addText(pk_org);// NC组织编码
		mainTable.addElement("billdate").addText(xhfydBean.getStr("RQ").substring(0, 10));// "2018-11-17"单据日期，注意格式
		mainTable.addElement("oldbillno").addText(xhfydBean.getStr("DJBH"));// 原单据号->对方系统单据号 待确定
		mainTable.addElement("scomment").addText(xhfydBean.getStr("BZ") == null ? "" : xhfydBean.getStr("BZ"));// 备注

		Element bodys = mainTable.addElement("bodys");
		int lineno = 0;

		for (Xhfymxd xhfymxd : listMx) {
			lineno++;
			Element item = bodys.addElement("item");
			item.addElement("itemid").addText(String.valueOf(lineno));// 明细行号
			Ncdzb dzb = ncdzbService.findById(xhfydBean.getStr("DM2"));
			if (dzb == null) {
				throw new Exception("NC供货商编码为空");
			}
			item.addElement("custsup").addText(dzb.getStr("NCMD"));// 供应商编码
			item.addElement("scomment").addText(xhfymxd.getStr("BZ"));// 摘要abc211（说明）
			item.addElement("subjcode").addText("112301");// 贷方科目编码
			item.addElement("pk_currtype").addText("CNY");// 默认CNY
			item.addElement("rate").addText("1");// 汇率，默认为1
			item.addElement("money").addText(xhfymxd.getStr("JE"));// 借方原币金额
			item.addElement("material").addText("");// NC物料编码
			String se = "";
			if (StringUtil.isNotBlank(xhfymxd.getStr("BYZD13"))) {
				Double je = Double.valueOf(xhfymxd.getStr("JE"));
				Double sl = Double.valueOf(xhfymxd.getStr("BYZD13"));
				se = String.valueOf(je * sl);
			}
			item.addElement("taxamount").addText(se);// 专票税额
			item.addElement("pk_deptid").addText("");// NC部门编码
			item.addElement("contractno").addText("");// 合同号
			item.addElement("busidate").addText(xhfydBean.getStr("RQ").substring(0, 10));// 起算日期，长度8位
			item.addElement("taxrate").addText("");// 税率
			String pp = xhfydBean.getStr("DM2").contains("T") == true ? "PP02" : "PP01";
			item.addElement("brands").addText(pp);// 品牌
		}
		return doucment;
	}

	public void syncupdate(String para) throws Exception {
		Xhfyd xhfydBean = dao.findById(para);
		// NCFSJL nf = fsjlservice.findById(para);
		String ncbillid = "";
		// if (nf != null) {
		// NCBILLID = nf.getStr("NCBILLID");
		// }
		Document doc = makeXhfydXml(xhfydBean, ncbillid);
		OutSideDataReceiveItf os = new OutSideDataReceiveItf();// NC配置类
		OutSideDataReceiveItfPortType datRecv = os.getOutSideDataReceiveItfSOAP11PortHttp();
		String str = datRecv.receiveXmlData(doc.asXML(), "RECBILL");
		String result = "0", comment = "";
		if (isXml(str)) {
			Document document = DocumentHelper.parseText(str);
			Element ele0 = document.getRootElement();
			Element ele1 = ele0.element("result");
			result = ele1.getTextTrim();
			Element ele2 = ele0.element("comment");
			comment = ele2.getTextTrim();
		}
		if (comment == "") {
			comment = str;
		}
		fsjlservice.insertNCFSJL(xhfydBean.getStr("DJBH"), doc.asXML(), result, str, comment);
	}

	public void syncupdates(String djbhs) throws Exception {
		String[] ids = djbhs.split(",");
		for (String str : ids) {
			syncupdate(str);
		}
	}
}
